{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 指定要整理的文件类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['txt', 'jpg', 'exe']"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "file_types = [\"txt\", \"jpg\", \"exe\"]\n",
    "file_types"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 给这些类型创建目录"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "for file_type in file_types:\n",
    "    os.mkdir(file_type)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 遍历文件移动到指定目录"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.txt\n",
      "2.txt\n",
      "3.txt\n",
      "4.jpg\n",
      "5.jpg\n",
      "6.jpg\n",
      "7.exe\n",
      "8.exe\n",
      "9.exe\n"
     ]
    }
   ],
   "source": [
    "# 遍历目录下的每个文件\n",
    "for filename in os.listdir(\"./\"):\n",
    "    # 遍历每个文件后缀类型\n",
    "    for file_type in file_types:\n",
    "        # 如果当前文件属于这个类型\n",
    "        if filename.endswith(\".\"+file_type):\n",
    "            print(filename)\n",
    "            # 就移动到对应目录\n",
    "            os.rename(\n",
    "                filename, \n",
    "                file_type + \"/\" + filename\n",
    "            )        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
